﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoadBalancerHandler.cs" company="SoftServe IT">
// handler for load balancer server mode
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace WebServer.BusinessLogic.Handlers
{
    using System;

    /// <summary>
    /// Load Balancer Handler
    /// </summary>
    public class LoadBalancerHandler : Handler
    {
        /// <summary>
        /// Redirects client to the least busy server.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The WebServer.BusinessLogic.Response.
        /// </returns>
        public override Response Handle(Request request)
        {
            if (Configurator.Instance.ServerMode == ServerConfiguration.LoadBalancer)
            {
                string addr = Communicator.Instance.LoadBalancer.LeastLoadedServer;
                if (addr == null)
                {
                    return this.NextHandler.Handle(request);
                }

                Response toReturn = new Response("text/html", request.HttpVersion, new byte[0]);
                toReturn.SetRedirect("http://" + addr);
                toReturn.Location = addr;
                toReturn.HttpResponseCode = 302;
                toReturn.HttpResponseCodeDescription = "Found";
                toReturn.Location = "http://" + addr;
                return toReturn;
            }

            return this.NextHandler.Handle(request);
        }
    }
}